package top.suyarong.ftbqsync.timer;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import top.suyarong.ftbqsync.FTBQSync;
import top.suyarong.ftbqsync.data.FtbMapper;
import top.suyarong.ftbqsync.data.entity.FtbQuestSync;
import top.suyarong.ftbqsync.utils.AstralSorceryUtil;
import top.suyarong.ftbqsync.utils.ConfigReader;
import top.suyarong.ftbqsync.utils.FTBQuestUtil;
import top.suyarong.ftbqsync.utils.LogUtil;

import java.util.*;

/**
 * 定时任务,保存玩家数据到数据库
 */
public class DataSaveTask extends Thread {

    public static final long PERIOD_TIME = ConfigReader.getTimerTime() * 60 * 1000;

    private static final LogUtil log = LogUtil.getInstance();

    private static final FTBQSync plugin = FTBQSync.getInstance();

    private static final FtbMapper mapper = FtbMapper.getInstance();

    private Timer timer;

    @Override
    public void run() {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, ConfigReader.getTimerTime());
        Date startTime = instance.getTime();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                log.info(plugin, "DataSaveTask ===> 正在同步当前在线玩家数据到数据库");
                long start = System.currentTimeMillis();
                Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
                if (onlinePlayers == null || onlinePlayers.size() <= 0) {
                    log.info(plugin, "&e当前没有玩家在线,结束同步");
                    return;
                }

                for (Player player : onlinePlayers) {
                    String playerName = player.getName();
                    byte[] playerQuestNbtData = FTBQuestUtil.getPlayerQuestNbtData(player);
                    byte[] astralData = AstralSorceryUtil.getData(player);
                    mapper.lockPlayer(FtbQuestSync.builder().playerName(playerName).build());
                    mapper.updatePlayer(FtbQuestSync.builder()
                            .playerName(playerName)
                            .ftbData(playerQuestNbtData)
                            .astralData(astralData)
                            .build());
                }

                log.info(plugin, "DataSaveTask ===> 玩家任务数据同步完成, 耗时 {} ms", System.currentTimeMillis() - start);
            }
        }, startTime, PERIOD_TIME);

    }

    public Timer getTimer() {
        return timer;
    }

}
